package edt;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JOptionPane;

import org.joda.time.DateTime;
import org.joda.time.LocalTime;

import com.google.gdata.client.GoogleService.InvalidCredentialsException;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.util.ServiceException;
import com.thirdnf.ResourceScheduler.Resource;

public class ViewListener implements ActionListener {

	MySchedulerModel model;
	MyScheduler scheduler;
	
	// The base URL for a user's calendar metafeed.
	private static final String METAFEED_URL_BASE = "https://www.google.com/calendar/feeds/";
	// The string to add to the user's metafeedUrl to access the event feed for
	// their primary calendar.
	private static final String EVENT_FEED_URL_SUFFIX = "/private/full";	
	// The URL for the metafeed of the specified user.
	private static URL metafeedUrl = null;
	// The URL for the event feed of the specified user's primary calendar.
	private static URL eventFeedUrl = null;
	
	public ViewListener(MyScheduler myScheduler, MySchedulerModel model) {
		this.scheduler=myScheduler;
		this.model = model;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		LinkedList<CreneauModele> creneaux = new LinkedList<CreneauModele>();
		CalendarService myService = new CalendarService("edt");
		
		String userName = scheduler.login.getText();
		String userPassword = scheduler.pass.getText();
		
		
		InetAddress Ip = null;
		try {
			Ip = InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	    
	    Properties prop = new Properties();
	    FileInputStream in = null;
		try {
			in = new FileInputStream("proxy.properties");
			prop.load(in); 
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String host = prop.getProperty("host"); 
		String port = prop.getProperty("port"); 
	    
	    if(host!=null && port!=null) {
	    	System.setProperty("https.proxyHost", host);
	    	System.setProperty("https.proxyPort", port);
	    }
		
		try {
		metafeedUrl = new URL(METAFEED_URL_BASE + userName);
		eventFeedUrl = new URL(METAFEED_URL_BASE + userName
		+ EVENT_FEED_URL_SUFFIX);
		} catch (MalformedURLException e) {
		      // Bad URL
		      System.err.println("Mauvais URL.");
		      e.printStackTrace();
		      return;
		    }
		
		try {
			myService.setUserCredentials(userName, userPassword);
			
//			CalendarEventFeed resultFeed = myService.getFeed(eventFeedUrl,
//					CalendarEventFeed.class);
			
			Calendar calendar = new GregorianCalendar();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			
			int difDeb = 2 - convertDay(calendar.get(Calendar.DAY_OF_WEEK));
			
			calendar.add(Calendar.DAY_OF_WEEK, difDeb);
			Date dateDebut = calendar.getTime();
			dateDebut.setHours(7);
			dateDebut.setMinutes(0);
			dateDebut.setSeconds(0);
			
			calendar.add(Calendar.DAY_OF_WEEK, 6);
			Date dateFin = calendar.getTime();

			
			CalendarEventFeed resultFeed = dateRangeQuery(myService, 
					com.google.gdata.data.DateTime.parseDate(format.format(dateDebut)), 
					com.google.gdata.data.DateTime.parseDate(format.format(dateFin)));
			
			for (int i = 0; i < resultFeed.getEntries().size(); i++) {
				
				
				try {
					CreneauModele creneau = new CreneauModele();
					CalendarEventEntry entry = resultFeed.getEntries().get(i);
					
					
					String[] sub = entry.getPlainTextContent().split(",");
					String type = sub[0].substring(5);
					String groupe = sub[1].substring(7);
					
					creneau.set_title(entry.getTitle().getPlainText());
					creneau.setGroupe(groupe);
					creneau.setType(type);
					creneau.setClasse(entry.getLocations().get(0).getValueString());
					
					
					
					
					DateTime debut = new DateTime(entry.getTimes().get(0).getStartTime().getValue());
					creneau.set_dateTime(new LocalTime(debut.getHourOfDay(),0,0));
					
					
					DateTime fin = new DateTime(entry.getTimes().get(0).getEndTime().getValue());
					int duree = fin.getMinuteOfDay() - debut.getMinuteOfDay();
					
					/*TODO
					 * Trouver la valeur dans le creneau de GOOGLE
					 */
					creneau.setDuration(duree);
					
						
					Date date = new Date(entry.getTimes().get(0).getStartTime().getValue());
					Calendar cal = new GregorianCalendar();
					cal.setTime(date);
					creneau.set_resource(convertIntDayToString(cal.get(Calendar.DAY_OF_WEEK)));
					
					creneau.setAlreadySync(true);
					creneaux.add(creneau);
					
					
				} catch (Exception e) {
					System.err.println("Creneau non valide");
				}
				
			}	

			Iterator<CreneauModele> ite = creneaux.iterator();
			
			while(ite.hasNext()) {
				model.addAppointment(ite.next());
			}
			
		} catch (InvalidCredentialsException e) {
	        System.out.println("Mauvais id ou mdp");
			JOptionPane.showMessageDialog(scheduler, "Mauvais identifiant ou mot de passe", "Erreur",
			        JOptionPane.ERROR_MESSAGE);		
	    } catch (IOException e) {
	        // Communications error
	        System.err.println("There was a problem communicating with the service.");
	        e.printStackTrace();
	    } catch (ServiceException e) {
	        // Server side error
	        System.err.println("The server had a problem handling your request.");
	        e.printStackTrace();
	    } 
		
		
		
	}
	
	/**
	* Prints the titles of all events in a specified date/time range.
	* 
	* @param service An authenticated CalendarService object.
	* @param startTime Start time (inclusive) of events to print.
	* @param endTime End time (exclusive) of events to print.
	* @throws ServiceException If the service is unable to handle the request.
	* @throws IOException Error communicating with the server.
	*/
	private static CalendarEventFeed dateRangeQuery(CalendarService service,
			com.google.gdata.data.DateTime startTime, com.google.gdata.data.DateTime endTime) 
			throws ServiceException, IOException {
		CalendarQuery myQuery = new CalendarQuery(eventFeedUrl);
		myQuery.setMinimumStartTime(startTime);
		myQuery.setMaximumStartTime(endTime);
		
		// Send the request and receive the response:
		CalendarEventFeed resultFeed = service.query(myQuery,
		CalendarEventFeed.class);
		
		System.out.println("Events from " + startTime.toString() + " to "
				+ endTime.toString() + ":");
		System.out.println();
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			CalendarEventEntry entry = resultFeed.getEntries().get(i);
			System.out.println("\t" + entry.getTitle().getPlainText());
		}
		System.out.println();
		return resultFeed;
	}
	
	public Resource convertIntDayToString(int jour) {
		//String day = "";
		if (jour==2) {
			return model.getLundi();
		} else if (jour==3) {
			return model.getMardi();
		} else if (jour==4) {
			return model.getMercredi();
		} else if (jour==5) {
			return model.getJeudi();
		} else {
			return model.getVendredi();
		} 
	}
	
	public static int convertDay(int javaDay) {
	 switch(javaDay) {
	    case Calendar.MONDAY: return 2;
	    case Calendar.TUESDAY: return 3;
	    case Calendar.WEDNESDAY: return 4;
	    case Calendar.THURSDAY: return 5;
	    case Calendar.FRIDAY: return 6;
	    case Calendar.SATURDAY: return 7;
	    case Calendar.SUNDAY: return 1;
	    default: throw new IllegalArgumentException("Illegal value for Calendar day of week: " + javaDay);
	 }
	}
	
}
